package com.shouhuobao.take.verify;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import com.app.city.AreaChooseActivity;
import com.app.city.util.AddressBean;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.Intents;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;
import com.shouhuobao.take.BaseActivityWithScroll;
import com.shouhuobao.take.model.StationDetailBean;
import com.shouhuobao.take.model.StationOpenInfoBean;

import droid.frame.utils.Android;

/**
 * 注册、审核第一步
 *
 * @author coffee<br>
 *         2017年6月26日下午2:10:37
 */
public class RegVerifyActivity1 extends BaseActivityWithScroll implements OnClickListener, BaiduMap.OnMapStatusChangeListener {

    private Button mSubmit;
    private EditText mStoreName, mStoreOwner, mStorePhone;
    private TextView mStoreAddress;
    private EditText mStoreAddressDetails;// 地址详细地址
    private ScrollView mScrollView;
    private StationOpenInfoBean stationBean = null;
    private boolean isFinish = true;
    /********************************地图相关*********************/
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LatLng mLatLng = null;
    private boolean isFirst = true;
    private Marker mMarker = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setScrollHeight(50);
        showLoadingDialog(null);
        AppHttp.getInstance().stationDetailData();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.reg_verify1);
        super.findViewById();
        getAppTitle().setCommonTitle("填写信息");
        mScrollView = (ScrollView) findViewById(R.id.content_layout);
        mStoreName = (EditText) findViewById(R.id.store_name);
        mStoreOwner = (EditText) findViewById(R.id.store_owner);
        mStorePhone = (EditText) findViewById(R.id.store_phone);
        mStoreAddress = (TextView) findViewById(R.id.store_address);
        mStoreAddressDetails = (EditText) findViewById(R.id.store_address_details);
        mSubmit = (Button) findViewById(R.id.submit);
        findViewById(R.id.store_address_LL).setOnClickListener(this);
        //
        mStoreAddress.setOnClickListener(this);
        mSubmit.setOnClickListener(this);
        stationBean = AppCache.getStationOpenInfoBean();
        if (stationBean == null) {
            stationBean = new StationOpenInfoBean();
            AppCache.setStationOpenInfoBean(stationBean);
        }
        setButtonEnableStyle(mSubmit, false);
        updateView(stationBean);
        mStoreName.addTextChangedListener(watcher);
        mStoreOwner.addTextChangedListener(watcher);
        mStorePhone.addTextChangedListener(watcher);
        mStoreAddress.addTextChangedListener(watcher);
        mStoreAddressDetails.addTextChangedListener(watcher);
        initMapView();
        showLoadingDialog("正在定位");
        Intents.startBaiduLocation(getContext(), null);
    }

    private void updateView(StationOpenInfoBean bean) {
        if (isNotEmpty(bean.getStationName())) {
            mStoreName.setText(bean.getStationName());
        }
        if (isNotEmpty(bean.getStationPersonName())) {
            mStoreOwner.setText(bean.getStationPersonName());
        }
        if (isNotEmpty(bean.getStationPhone())) {
            mStorePhone.setText(bean.getStationPhone());
        }
        if (isNotEmpty(bean.getStationArea())) {
            mStoreAddress.setText(bean.getStationArea());
        }
        if (isNotEmpty(bean.getStationAddressDetail())) {
            mStoreAddressDetails.setText(bean.getStationAddressDetail());
        }
    }

    private TextWatcherExt watcher = new TextWatcherExt() {
        public void afterTextChanged(android.text.Editable s) {
            if (isNotEmpty(mStoreName.getText().toString()) && isNotEmpty(mStoreOwner.getText().toString()) //
                    && isNotEmpty(mStorePhone.getText().toString()) && isNotEmpty(mStoreAddress.getText().toString())
                    && isNotEmpty(mStoreAddressDetails.getText().toString())) {//&& mLatLng != null
                mSubmit.setBackgroundColor(getResources().getColor(R.color.app_font_green));
            } else {
                mSubmit.setBackgroundColor(getResources().getColor(R.color.app_font_white2));
            }
        }
    };

    /**
     * 初始化地图相关控件
     */
    private void initMapView() {
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mMapView.showZoomControls(false);//隐藏缩放按钮
        mMapView.showScaleControl(false);//隐藏比例尺
        mBaiduMap.setMyLocationEnabled(true);
        mMapView.getChildAt(0).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    mScrollView.requestDisallowInterceptTouchEvent(false);
                } else { //不允许ScrollView截断点击事件，点击事件由子View处理
                    mScrollView.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
        //设置地图状态监听
        mBaiduMap.setOnMapStatusChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 选择省市区
            case R.id.store_address_LL:
            case R.id.store_address:
                Intent intent = new Intent();
                intent.setClass(getContext(), AreaChooseActivity.class);
                startActivityForResult(intent, 103);
                break;
            case R.id.submit:
                if (isEmpty(mStoreName.getText())) {
                    showToast("请输入店铺名称");
                    return;
                }
                if (isEmpty(mStoreOwner.getText())) {
                    showToast("请输入负责人姓名");
                    return;
                }
                if (isEmpty(mStorePhone.getText())) {
                    showToast("请输入手机号码");
                    return;
                }
                if (isEmpty(mStoreAddress.getText())) {
                    showToast("请输入所在城市区");
                    return;
                }
                if (isEmpty(mStoreAddressDetails.getText())) {
                    showToast("请输入详细地址");
                    return;
                }
                if (mLatLng == null) {
                    showToast("获取店面坐标失败");
                    return;
                }
                String[] areaStr = mStoreAddress.getText().toString().split(" ");
                if (areaStr == null && areaStr.length == 0) {
                    return;
                }
                showLoadingDialog(null);
                AppHttp.getInstance().submitStationInfoData(mStoreName.getText().toString(), mStoreOwner.getText().toString(),
                        mStorePhone.getText().toString(), areaStr[0], areaStr[1], areaStr[2], mStoreAddressDetails.getText().toString(),
                        mLatLng.latitude + "", mLatLng.longitude + "");
                break;
        }
    }

    private void addMarkToMap(LatLng latLng) {
        if (mMarker != null) {
            mMarker.remove();
        }
        BitmapDescriptor bdB = BitmapDescriptorFactory.fromResource(R.drawable.info_map_icon);
        OverlayOptions ooB = new MarkerOptions().position(latLng).icon(bdB).zIndex(9).draggable(true);
        //将marker添加到地图上
        mMarker = (Marker) (mBaiduMap.addOverlay(ooB));
//        mMapView.getMap().addOverlay(ooB);
        int zoomLevel = 17;// 缩放级别14-1公里, 15-500米
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(latLng, zoomLevel);
        mMapView.getMap().animateMapStatus(u);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //百度定位
            case MsgID.location_baidu:
                cancelLoadingDialog();
                BDLocation location = (BDLocation) msg.obj;
                if (location == null) {
                    showToast("定位失败");
                } else {
                    mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                    addMarkToMap(mLatLng);
                }
                return false;
            //提交资料
            case MsgID.station_open_info_submit:
                cancelLoadingDialog();
                final ReqResult<?> reqResult = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(reqResult)) {
                            isFinish = false;
                            showToast("提交成功");
                            AppCache.setStationOpenInfoBean(null);
                            finish();
                        } else {
                            showToast(reqResult.getMessage());
                        }
                    }
                });
                return true;
            case MsgID.query_station_info:
                cancelLoadingDialog();
                final ReqResult<StationDetailBean> result = JSON.parser(msg.obj, StationDetailBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result)) {
                            StationDetailBean stationDetail = result.getResult();
                            if (stationDetail != null) {
                                StationOpenInfoBean bean = new StationOpenInfoBean();
                                bean.setStationName(stationDetail.getName());
                                bean.setStationPersonName(stationDetail.getAdmin());
                                bean.setStationArea(stationDetail.getCity());
                                bean.setStationAddressDetail(stationDetail.getAddress());
                                bean.setStationPhone(stationDetail.getPhone());
                                bean.setLat(stationDetail.getLatitude());
                                bean.setLng(stationDetail.getLongitude());
                                bean.setStationHousingEstateName(stationDetail.getCommunity());
                                bean.setStationOpenTime(stationDetail.getServiceTime());
                                bean.setStationAreaNum(stationDetail.getArea());
                                bean.setStationWXNum(stationDetail.getWeixin());
                                AppCache.getUser().setLevel(stationDetail.getLevel());
                                AppCache.setStationOpenInfoBean(bean);
                                updateView(bean);
                            }
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 选择省市区
        if (resultCode == Activity.RESULT_OK && requestCode == 103) {
            AddressBean result = (AddressBean) data.getSerializableExtra("item");
            stationBean.setStationArea(result.getProvince() + " " + result.getCity() + " " + result.getDistrict());
            AppCache.setStationOpenInfoBean(stationBean);
            mStoreAddress.setText(result.getProvince() + " " + result.getCity() + " " + result.getDistrict());
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void finish() {
        if (isFinish) {
            stationBean.setStationName(mStoreName.getText().toString());
            stationBean.setStationPersonName(mStoreOwner.getText().toString());
            stationBean.setStationPhone(mStorePhone.getText().toString());
            stationBean.setStationArea(mStoreAddress.getText().toString());
            stationBean.setStationAddressDetail(mStoreAddressDetails.getText().toString());
            if (mLatLng != null) {
                stationBean.setLat(mLatLng.latitude);
                stationBean.setLng(mLatLng.longitude);
            }
            AppCache.setStationOpenInfoBean(stationBean);
        }
        super.finish();
    }

    @Override
    protected void onResume() {
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mMapView.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        Android.hideSoftInput(getContext());
        if (mMarker != null) {
            mMarker.remove();
        }
        if (mBaiduMap != null) {
            // 关闭定位图层
            mBaiduMap.setMyLocationEnabled(false);
            mBaiduMap.clear();
        }
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
        }
        super.onDestroy();
    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {
        if (mMarker != null) {
            mLatLng = mapStatus.target;
            mMarker.setPosition(mapStatus.target);
        }
    }
}
